#include "config.h"
#include "Arduino.h"

bool isConnectWiFi = false;

//wifiSTAConnectBegin通过账号密码连接wifi,waitTime表示等待多久的wifi连接，waitTime单位是毫秒
void wifiSTAConnectBegin(const char* ssid, const char* password,int waitTime) {
  int waitCount=0;
  if (isConnectWiFi == false) {
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED&&waitCount<waitTime) {
      delay(500);
      waitCount++;
      Serial.print(".");
    }
    if(WiFi.status() != WL_CONNECTED){
      disconnectWiFi();
      return;
    }
    else
    {
      Serial.println("");
      Serial.println("WiFi connected.");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      isConnectWiFi = true;
      saveWifiSTA(ssid,password);
      #ifdef _SQUARELINE_PROJECT_UI_H
        lv_obj_add_state(ui_ScSetSwitch, LV_STATE_CHECKED);
        lv_label_set_text(ui_ScSetWifiId, ssid);
        #endif
      return;
    }

  }
  return;
  //  Serial.println("hello");
}

void disconnectWiFi() {
  WiFi.disconnect(true); // Disconnect from the current network and forget the credentials
  WiFi.mode(WIFI_OFF);   // Turn off the WiFi module
  isConnectWiFi=false;
  #ifdef _SQUARELINE_PROJECT_UI_H
    lv_obj_clear_state(ui_ScSetSwitch, LV_STATE_CHECKED);
    lv_label_set_text(ui_ScSetWifiId, "......");
    #endif
}

void reinstallWifi(){
  Serial.println("reinstallWifi work");
  EEPROM.write(wifi_sta_id, '\0');
  EEPROM.write(wifi_sta_pwd, '\0');
  EEPROM.commit();
}

void saveWifiSTA(const char* ssid, const char* password){
  Serial.println("saveWifiSTA work");
  Serial.println(ssid);
  Serial.println(password);
  int i=0;
  while(ssid[i]!='\0'){
    EEPROM.write(wifi_sta_id+i,ssid[i]);
    i++;
  }
  i=0;
  EEPROM.write(wifi_sta_pwd+i,'\0');
  while(password[i]!='\0'){
    EEPROM.write(wifi_sta_pwd+i,password[i]);
    i++;
  }
  EEPROM.write(wifi_sta_id+i,'\0');
  EEPROM.commit();
  // EEPROM.put(wifi_sta_id, ssid);
  // EEPROM.put(wifi_sta_pwd, password);
}

String* getWifiSTA(){
  char ssid[32], password[32];
  String* wifiSTAdata=new String[2];
  EEPROM.get(wifi_sta_id, ssid);
  EEPROM.get(wifi_sta_pwd, password);
  Serial.println("try to read wifiData");
  Serial.println(ssid);
  Serial.println(password);
  wifiSTAdata[0]=String(ssid);
  wifiSTAdata[1]=String(password);
  Serial.println(wifiSTAdata[0]);
  Serial.println(wifiSTAdata[1]);
  return wifiSTAdata;
}

void wifiSetup(){
  if (isFirstUse == true) {
    reinstallWifi();
  }
  else{
    #ifdef _SQUARELINE_PROJECT_UI_H
      lv_obj_add_event_cb(ui_wifiPanelSave, ui_myEvent_scWLwifiPanelSave, LV_EVENT_CLICKED, NULL);
      lv_obj_add_event_cb(ui_ScSetSwitch, ui_myEvent_ui_ScSetSwitch, LV_EVENT_VALUE_CHANGED, NULL);
      #endif
    String* wifiSTAdata;
    wifiSTAdata=getWifiSTA();
    if (wifiSTAdata != nullptr && wifiSTAdata[0].length() > 0 && wifiSTAdata[1].length() > 0) {
      wifiSTAConnectBegin(wifiSTAdata[0].c_str(), wifiSTAdata[1].c_str(), 10);
    }
    if(!isConnectWiFi){
      disconnectWiFi();
    }
  }

}

#ifdef _SQUARELINE_PROJECT_UI_H



void ui_myEvent_scWLwifiPanelSave(lv_event_t* e) {
  const char *id=lv_textarea_get_text(ui_wifiIdText);
  const char *pwd=lv_textarea_get_text(ui_wifiPasswordText);
  _ui_flag_modify(ui_wifiPopups, LV_OBJ_FLAG_HIDDEN, _UI_MODIFY_FLAG_REMOVE);
  lv_label_set_text(ui_wifiIDText, id);
  lv_label_set_text(ui_wifiConnectMsg, "正在连接，请稍等");
  lv_task_handler(); /* let the GUI do its work */
  delay(100);
  wifiSTAConnectBegin(id,pwd,10);
  if(!isConnectWiFi){
    lv_label_set_text(ui_wifiConnectMsg, "连接失败，请再试一下");
  }
  else{
    lv_label_set_text(ui_wifiConnectMsg, "连接成功！");
  }
}

void ui_myEvent_ui_ScSetSwitch(lv_event_t* e){
  lv_obj_t* obj = lv_event_get_target(e);
  if(lv_obj_has_state(obj, LV_STATE_CHECKED)){
    String* wifiSTAdata;
    wifiSTAdata=getWifiSTA();
    if (wifiSTAdata != nullptr && wifiSTAdata[0].length() > 0 && wifiSTAdata[1].length() > 0) {
      wifiSTAConnectBegin(wifiSTAdata[0].c_str(), wifiSTAdata[1].c_str(), 10);
    }else{
    disconnectWiFi();
  }
  }else{
    disconnectWiFi();
  }
}

#endif